import { observable, action, makeObservable } from 'mobx';
import { v4 as uuidV4 } from 'uuid';
import dayjs from 'dayjs';

interface ITodo {
  key: string;
  time: string;
  text: string;
}

class Todo {
  constructor() {
    makeObservable(this, {
      list: observable,
      add: action,
      delete: action,
      update: action
    })
  }

  // @observable
  list: Array<ITodo> = [];

  // @action
  add(text: string) {
    this.list.push({
      key: uuidV4(),
      text: text,
      time: dayjs().format('YYYY-MM-DD HH:mm')
    });
  }

  // @action
  update(key: string, text: string) {
    const index = this.list.findIndex(item => item.key === key);
    this.list[index].text = text;
  }

  delete(key: string) {
    this.list = this.list.filter((item: ITodo) => item.key !== key);
  }
}

export default new Todo();
export const todo = new Todo();
